package com.health.mapp.service;

import com.health.db.dto.StuffDetailDto;
import com.health.db.model.ImMsgNoticeExample;
import com.health.db.model.UserLIST;
import com.health.db.service.msg.ImMsgNoticeService;
import com.health.db.service.user.IStuffListService;
import com.health.db.service.user.IUserLISTService;
import com.health.mapp.bean.GetSMSResp;
import com.health.mapp.utils.Constant;
import com.health.mapp.utils.DateUtils;
import com.health.mapp.utils.ResultCode;
import com.taobao.api.ApiException;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.request.AlibabaAliqinFcSmsNumSendRequest;
import com.taobao.api.response.AlibabaAliqinFcSmsNumSendResponse;
import net.sf.json.JSONObject;
import org.apache.http.util.TextUtils;
import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

public class GetBindSmsCode extends HttpServlet{

    private IStuffListService stuffListService;
    private ImMsgNoticeService imMsgNoticeService  ;
    private static Logger logger = Logger.getLogger(GetBindSmsCode.class);

    public void init(ServletConfig config) throws ServletException {
        SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
                config.getServletContext());
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        ServletContext servletContext = request.getSession().getServletContext();
        ApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);

        GetSMSResp _resp=new GetSMSResp() ;


        String sign,time,phone;
        phone=request.getParameter("number");
        time=request.getParameter("timestamp");
        sign=request.getParameter("sign");

        if (TextUtils.isEmpty(phone)||TextUtils.isEmpty(time)||TextUtils.isEmpty(sign))
        {
            _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
            _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);

            logger.error("跨域访问缺少相关参数 phone time sign");
        }else
        {
            try {
                long number = Long.valueOf(time);
                int index = (int)(number % 10);
                String msg = phone + number + SecureUtil.getChallenge(index);
                //信息摘要
                MessageDigest md5 = MessageDigest.getInstance("MD5");
                //使用指定的 byte 数组更新摘要
                md5.update(msg.getBytes());
                //通过执行诸如填充之类的最终操作完成哈希计算。
                byte[] buffer = md5.digest();
                //bcd码转为String
                String signaaa = bcd2Str(buffer);
                logger.debug("sign:"+ signaaa);
                if (true != sign.equalsIgnoreCase(signaaa)) {
                    _resp.setErrorCode(Constant.CODE_REQ_JSON_SIGN_ERR);
                    _resp.setErrorMsg(Constant.MSG_REQ_JSON_SIGN_ERR);
                }


                String radom = String.valueOf(Math.round(Math.random()*900000+100000));
                TaobaoClient clients = new DefaultTaobaoClient("http://gw.api.taobao.com/router/rest", "23312748", "d7badcea8b88c4560868f1a4e3c246c9");
                AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
                req.setExtend(radom);
                req.setSmsType("normal");
                req.setSmsFreeSignName("首儿健康汇");
                req.setSmsParamString("{\"code\":\" "+radom +"\",\"product\":\"首儿健康汇\"}");
                req.setRecNum(phone);

                stuffListService= (IStuffListService) applicationContext.getBean("stuffListService");
                imMsgNoticeService= (ImMsgNoticeService) applicationContext.getBean("imMsgNoticeService");
                StuffDetailDto stuffDetailDto=stuffListService.selectByStuffNo(phone);

                if (null!=stuffDetailDto)
                {
                    req.setSmsTemplateCode("SMS_5053416");

                    AlibabaAliqinFcSmsNumSendResponse rsp;
                    try {
                        rsp = clients.execute(req);
                        String responseS =rsp.getBody();
                        JSONObject jsStr = JSONObject.fromObject(responseS);
                        JSONObject errorResponse =  JSONObject.fromObject( jsStr.get("error_response"));

                        if (null!=errorResponse&&(!"null".equals(errorResponse.toString()))) {
                            _resp.setErrorCode(-1);
                            _resp.setErrorMsg("发送失败请稍后重试");
                        }
                        JSONObject resultStr =JSONObject.fromObject( jsStr.get("alibaba_aliqin_fc_sms_num_send_response"));
                        JSONObject reStr    =JSONObject.fromObject( resultStr.get("result"));
                        int errid = Integer.parseInt((String) reStr.get("err_code"));

                        if (String.valueOf("0").equals((String) reStr.get("err_code")))
                        {
                            _resp.setSms(radom);
                        }
                        else
                        {
                            _resp.setErrorCode(-1);
                            _resp.setErrorMsg("发送失败请稍后重试");
                        }
                    } catch (ApiException e) {
                        _resp.setErrorCode(-1);
                        _resp.setErrorMsg("发送失败请稍后重试");
                    }

                    ImMsgNoticeExample notice = new ImMsgNoticeExample();
                    notice.setRandom(radom);
                    notice.setNoticeReceiveAddress(phone);
                    notice.setSendReceiveFlag((short) 9);
                    notice.setIsUsedFlag((short) 1);
                    notice.setCreateDate(DateUtils.now());
                    notice.setModetypeid(9);
                    imMsgNoticeService.insert(notice);

                }else
                {
                    _resp.setErrorCode(-1);
                    _resp.setErrorMsg("注册信息不存在");
                }


            }catch (Exception e)
            {
                logger.error(e.getMessage());
                _resp.setErrorCode(ResultCode.OPERATION_LAKE_PARAMETER_ERROR);
                _resp.setErrorMsg(ResultCode.OPERATION_LAKE_PARAMETER_ERROR_NOTE);
            }
        }

        String callbackName = request.getParameter("jsonpCallback");// 客户端请求参数
        String jsonStr = JSONObject.fromObject(_resp).toString();
        String renderStr = callbackName+"("+jsonStr+")";
        response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,PUT,DELETE");
        response.setHeader("Access-Control-Allow-Headers", "cache-control,content-type,hash-referer,x-requested-with");
        response.setContentType("application/json");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        out.print(renderStr);
        out.println("\r\n");
        out.flush();
        out.close();

    }


    private static String bcd2Str(byte[] bytes) {
        char temp[] = new char[bytes.length * 2], val;

        for (int i = 0; i < bytes.length; i++) {
            val = (char) (((bytes[i] & 0xf0) >> 4) & 0x0f);
            temp[i * 2] = (char) (val > 9 ? val + 'A' - 10 : val + '0');

            val = (char) (bytes[i] & 0x0f);
            temp[i * 2 + 1] = (char) (val > 9 ? val + 'A' - 10 : val + '0');
        }

        return new String(temp);
    }

}
